﻿using System.Collections.Generic;
using System.Globalization;
using Dndz.Industries.Models;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;

namespace Dndz.Industries.Settings
{
    public class ContainerSettingsHooks : ContentDefinitionEditorEventsBase
    {
        public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition)
        {
            if (definition.PartDefinition.Name != typeof(CaptchaPart).Name)
                yield break;

            var model = definition.Settings.GetModel<CaptchaTypePartSettings>();

            yield return DefinitionTemplate(model);
        }

        public override IEnumerable<TemplateViewModel> TypePartEditorUpdate(
            ContentTypePartDefinitionBuilder builder, IUpdateModel updateModel)
        {
            if (builder.Name != typeof(CaptchaPart).Name)
                yield break;

            var model = new CaptchaTypePartSettings();
            updateModel.TryUpdateModel(model, "CaptchaTypePartSettings", null, null);
            builder.WithSetting("CaptchaTypePartSettings.Foreground", model.Foreground.ToString());
            builder.WithSetting("CaptchaTypePartSettings.Background", model.Background.ToString());
            builder.WithSetting("CaptchaTypePartSettings.TotalChars", model.TotalChars.ToString());
            builder.WithSetting("CaptchaTypePartSettings.ImageHeight", model.ImageHeight.ToString());
            builder.WithSetting("CaptchaTypePartSettings.ImageWidth", model.ImageWidth.ToString());
            builder.WithSetting("CaptchaTypePartSettings.ImageFont", model.ImageFont);
            builder.WithSetting("CaptchaTypePartSettings.YAmp", model.YAmp.ToString(CultureInfo.InvariantCulture));
            builder.WithSetting("CaptchaTypePartSettings.XAmp", model.XAmp.ToString(CultureInfo.InvariantCulture));
            builder.WithSetting("CaptchaTypePartSettings.IncLetters", model.IncLetters.ToString());
            builder.WithSetting("CaptchaTypePartSettings.IncDigits", model.IncDigits.ToString());
            builder.WithSetting("CaptchaTypePartSettings.IsForNotAuthUsersOnly", model.IsForNotAuthUsersOnly.ToString());

            yield return DefinitionTemplate(model);
        }
    }
}
